package com.cloudcc.mobile.bull;


import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.cloudcc.cloudframe.bus.BaseEvent;
import com.cloudcc.cloudframe.bus.DynamicEventList;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.util.DateUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.bull.bean.ShopBean;
import com.cloudcc.mobile.bull.utils.DiaUtils;
import com.cloudcc.mobile.bull.utils.ImgSmallUtils;
import com.cloudcc.mobile.dao.BullXiangGuanDao;
import com.cloudcc.mobile.dao.impl.BullXiangGuanImpl;
import com.cloudcc.mobile.dialog.BullListDialog;
import com.cloudcc.mobile.dialog.MakeTureDialog;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.BullGzlxEntity;
import com.cloudcc.mobile.entity.BullJxsNewJob;
import com.cloudcc.mobile.entity.map.MapLocation;
import com.cloudcc.mobile.event.BeauEventList;
import com.cloudcc.mobile.manager.LocationManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.DynamicControl;
import com.cloudcc.mobile.util.AppUtil;
import com.cloudcc.mobile.util.ImageUtil;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.photo.Constants;
import com.cloudcc.mobile.util.photo.Util;
import com.cloudcc.mobile.view.activity.BindActivity;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mypage.view.datedialog.DateTimeUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.cloudcc.mobile.R.id.bull_address_tv;
import static com.cloudcc.mobile.R.id.jxs_bull;
import static com.cloudcc.mobile.R.id.md_bull;
import static com.cloudcc.mobile.R.id.qkms_bull;

/**
 * Created by lin on 2017/10/25.
 */

public class BullNewJobActivity extends BaseActivity implements View.OnClickListener, IEventLife, BullListDialog.ChangeListener {

    @Bind(R.id.newjob_back)
    ImageView newjobBack;
    @Bind(R.id.newjob_save)
    Button newjobSave;
    @Bind(jxs_bull)
    TextView jxsBull;
    @Bind(md_bull)
    TextView mdBull;
    @Bind(R.id.bull_job_type)
    TextView bullJobType;
    @Bind(R.id.image1_bull)
    ImageView image1Bull;
    @Bind(R.id.image2_bull)
    ImageView image2Bull;
    @Bind(R.id.image3_bull)
    ImageView image3Bull;
    @Bind(R.id.image4_bull)
    ImageView image4Bull;
    @Bind(qkms_bull)
    EditText qkmsBull;
    @Bind(bull_address_tv)
    TextView bullAddressTv;
    @Bind(R.id.bull_address_layout)
    LinearLayout bullAddressLayout;
    @Bind(R.id.start_time)
    Button starttime;
    @Bind(R.id.end_time)
    Button endtime;
    @Bind(R.id.ll_jxs_md)
    LinearLayout ll_jxs_md; //经销商和门店是否隐藏
    private String zuobiao;
    private String imagename;
    private List<AddImageInfo> imageArray = new ArrayList<AddImageInfo>();
    private List<AddImageInfo> imageArray2 = new ArrayList<AddImageInfo>();
    private List<AddImageInfo> imageArray3 = new ArrayList<AddImageInfo>();
    private List<AddImageInfo> imageArray4 = new ArrayList<AddImageInfo>();
    //单张图片，list
    private List<AddImageInfo> imageArrayAll = new ArrayList<AddImageInfo>();
    private Map<String, String> jsonlist;
    private String mEns = RunTimeManager.getInstance().getlanguage();
    private BullXiangGuanDao bullDao;
    private String jxsId;//选择的经销商id
    private static final int TAKE_PHOTO_1 = 5001;
    private static final int TAKE_PHOTO_2 = 5002;
    private static final int TAKE_PHOTO_3 = 5003;
    private static final int TAKE_PHOTO_4 = 5004;
    private List<BullJxsNewJob> listJxs, listMenD;
    private List<BullGzlxEntity> listGzjl;
    private ImageLoadingListener animateFirstListener = new Util.AnimateFirstDisplayListener();
    private BullListDialog changeDialog;
    private MakeTureDialog makeTureDialog;
    //图片上传
    private DynamicControl dynamicControl = new DynamicControl();
    private boolean haveJxs = false, haveGzlx = false;
    private String isxunjian = "notye";
    public MapLocation currentLoc = new MapLocation();// 位置

    private String mDatime;
    private String mdid;
    boolean isTp;

    private boolean isSave = false;
    String filePaths;

    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);

        bullDao = new BullXiangGuanImpl();
        listJxs = new ArrayList<>();
        listMenD = new ArrayList<>();
        changeDialog = new BullListDialog(this, R.style.DialogLoadingTheme, this);
        makeTureDialog = new MakeTureDialog(this, R.style.DialogLoadingTheme);
        register();
        initLocation();
        initLister();
        initdata();
        setTimeStr();
    }

    private void initdata() {
        BeauEventList.BullJxsEvent Event = new BeauEventList.BullJxsEvent();//查询经销商
        bullDao.BullgetJxs("Account", "", "khmc,name", Event);
        BeauEventList.BullGzlxEvent Event2 = new BeauEventList.BullGzlxEvent();//查询工作类型
        String data = "{\"objectApiName\":\"gzjl\",\"fieldApi\":\"gzlx\",\"recordType\":\"\"}";
        bullDao.BullgetGzlx(data, Event2);

        if ("经销商".equals(getIntent().getStringExtra("title"))) {
            jxsBull.setText(getIntent().getStringExtra("name"));
            jxsId = getIntent().getStringExtra("id");
            Log.d("---", getIntent().getStringExtra("name") + getIntent().getStringExtra("id") + "--");
        }
        if ("门店".equals(getIntent().getStringExtra("title"))) {
            mdBull.setText(getIntent().getStringExtra("name"));
            mdid = getIntent().getStringExtra("id");
            getJxs();
            Log.d("---", getIntent().getStringExtra("name") + getIntent().getStringExtra("id") + "--");
        }
    }

    private void initLister() {
        newjobBack.setOnClickListener(this);
        newjobSave.setOnClickListener(this);
        jxsBull.setOnClickListener(this);
        mdBull.setOnClickListener(this);
        bullJobType.setOnClickListener(this);
        image1Bull.setOnClickListener(this);
        image2Bull.setOnClickListener(this);
        image3Bull.setOnClickListener(this);
        image4Bull.setOnClickListener(this);
        starttime.setOnClickListener(this);
        endtime.setOnClickListener(this);
    }

    public void onEventMainThread(BeauEventList.BullJxsEvent event) {

        listJxs = event.getData();
        if (listJxs != null && listJxs.size() != 0) {//查询到经销商
            haveJxs = true;
        } else {//没有查到经销商
            haveJxs = false;
        }
    }

    public void onEventMainThread(BeauEventList.BullMenDianEvent event) {

        listMenD = event.getData();
        if (listMenD != null && listMenD.size() != 0) {//查询到门店
            changeDialog.show();
            changeDialog.setDataMD(listMenD);
        } else {//没有查到门店
            makeTureDialog.show();
            makeTureDialog.setTitle("没有适合的门店");
        }
    }

    public void onEventMainThread(BeauEventList.BullGzlxEvent event) {

        listGzjl = event.getData();
        if (listGzjl != null && listGzjl.size() != 0) {//查询到工作记录
            haveGzlx = true;
        } else {//没有查到工作记录
            haveGzlx = false;
        }
    }


    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_bull_new_job;
    }

    private void initLocation() {
        LocationManager.getInstance().registerListener(mListener);
        LocationManager.getInstance().requestLocal();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public static void bubbleSort(int[] numbers) {
        int temp = 0;
        int size = numbers.length;
        for (int i = 0; i < size - 1; i++) {
            for (int j = 0; j < size - 1 - i; j++) {
                if (numbers[j] > numbers[j + 1])  //交换两数位置
                {
                    temp = numbers[j];
                    numbers[j] = numbers[j + 1];
                    numbers[j + 1] = temp;
                }
            }
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.newjob_back:// 返回
                finish();
                break;
            case R.id.newjob_save://保存
                if (TextUtils.isEmpty(bullJobType.getText().toString())) {
                    Toast.makeText(BullNewJobActivity.this, "工作类型不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if("工作日报".equals(bullJobType.getText().toString())||"工作记录".equals(bullJobType.getText().toString())||"非固定线".equals(bullJobType.getText().toString())){

                }else {
                if (TextUtils.isEmpty(jxsBull.getText().toString())) {
                    Toast.makeText(BullNewJobActivity.this, "请选择经销商", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("门店拜访".equals(bullJobType.getText().toString())) {
                    if (TextUtils.isEmpty(mdBull.getText().toString())) {
                        Toast.makeText(BullNewJobActivity.this, "请选择门店", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                }
                if("".equals(qkmsBull.getText().toString())){
                    Toast.makeText(this, "情况描述不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                isSave = true;
                showWainting("正在定位");
                initLocation();

                break;
            case jxs_bull://经销商
                if (haveJxs) {
                    changeDialog.show();
                    changeDialog.setDataJXS(listJxs);
                } else {
                    makeTureDialog.show();
                    makeTureDialog.setTitle("没有适合的经销商");
                }
                break;
            case md_bull://门店
                BeauEventList.BullMenDianEvent event = new BeauEventList.BullMenDianEvent();//查询门店
                bullDao.BullgetMenD("mendian", "dyjxs='" + jxsId + "'", "name,dzzb", event);
                break;
            case R.id.bull_job_type://工作类型
                if (haveGzlx) {
                    changeDialog.show();
                    changeDialog.setDataGZJL(listGzjl);
                } else {
                    makeTureDialog.show();
                    makeTureDialog.setTitle("无工作类型");
                }
                break;
            case R.id.image1_bull://图片1
                if ("门店拜访".equals(bullJobType.getText().toString())||"非固定线".equals(bullJobType.getText().toString())) {
                    isTp = true;
                    takePhoto(TAKE_PHOTO_1);
                    return;
                }
                DiaUtils.cameraPick(this, new DiaUtils.Res2() {
                    @Override
                    public void res(int i) {
                        if (i == 1) {
                            isTp = false;
                            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, TAKE_PHOTO_1);
                        } else {
                            isTp = true;
                            takePhoto(TAKE_PHOTO_1);
                        }
                    }
                });
                break;
            case R.id.image2_bull://图片2
                if ("门店拜访".equals(bullJobType.getText().toString())||"非固定线".equals(bullJobType.getText().toString())) {
                    isTp = true;
                    takePhoto(TAKE_PHOTO_2);
                    return;
                }
                DiaUtils.cameraPick(this, new DiaUtils.Res2() {
                    @Override
                    public void res(int i) {
                        if (i == 1) {
                            isTp = false;
                            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, TAKE_PHOTO_2);
                        } else {
                            isTp = true;
                            takePhoto(TAKE_PHOTO_2);
                        }
                    }
                });

                break;
            case R.id.image3_bull://图片1
                if ("门店拜访".equals(bullJobType.getText().toString())||"非固定线".equals(bullJobType.getText().toString())) {
                    isTp = true;
                    takePhoto(TAKE_PHOTO_3);
                    return;
                }
                DiaUtils.cameraPick(this, new DiaUtils.Res2() {
                    @Override
                    public void res(int i) {
                        if (i == 1) {
                            isTp = false;
                            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, TAKE_PHOTO_3);
                        } else {
                            isTp = true;
                            takePhoto(TAKE_PHOTO_3);
                        }
                    }
                });
                break;
            case R.id.image4_bull://图片2
                if ("门店拜访".equals(bullJobType.getText().toString())||"非固定线".equals(bullJobType.getText().toString())) {
                    isTp = true;
                    takePhoto(TAKE_PHOTO_4);
                    return;
                }
                DiaUtils.cameraPick(this, new DiaUtils.Res2() {
                    @Override
                    public void res(int i) {
                        if (i == 1) {
                            isTp = false;
                            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, TAKE_PHOTO_4);
                        } else {
                            isTp = true;
                            takePhoto(TAKE_PHOTO_4);
                        }
                    }
                });
                break;

            case R.id.start_time:
                if ("非固定线".equals(bullJobType.getText().toString())) {

                }else {
                    // 弹出
                    DateTimeUtil.initSelectTimePopuwindow(mContext,
                            starttime, false);

                }

                break;
            case R.id.end_time:
                // 弹出
                DateTimeUtil.initSelectTimePopuwindow(mContext,
                        endtime, false);
                break;
        }
    }

    public void setTimeStr() {

        Calendar starts = Calendar.getInstance();
        int crrentHour = starts.get(Calendar.HOUR);
//        if(!"".equals(mDatime)) {
//
//        }
//            starts.setTime(DateUtils.stringToDate(mDatime, "yyyy-MM-dd HH:mm:ss"));
//            starts.set(Calendar.HOUR, crrentHour);
        //starts.set(Calendar.MINUTE, 0);
        //starts.set(Calendar.SECOND, 0);
      //  starts.add(Calendar.HOUR, 1);
        starttime.setText(DateUtils.dateToString(starts.getTime(),
                "yyyy-MM-dd HH:mm:ss"));
        starts.add(Calendar.HOUR, 1);
        endtime.setText(DateUtils.dateToString(starts.getTime(),
                "yyyy-MM-dd HH:mm:ss"));

    }

    @Override
    protected void onDestroy() {
        LocationManager.getInstance().unregisterlistener(mListener);
        unRegister();
        super.onDestroy();
    }

    private void refreshTvAddress() {
        if (null != lastDBLocation) {
            bullAddressTv.setText(LocationManager.getDetailAddr(lastDBLocation,
                    false));
        } else {
            if ("en".equals(mEns)) {
                bullAddressTv.setText("Is positioning.....");
            } else {
                bullAddressTv.setText("正在定位.....");
            }

        }
    }

    private BDLocation lastDBLocation;
    private BDLocationListener mListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location
                    && location.getLocType() != BDLocation.TypeServerError) {
                if ("4.9E-324".equals(String.valueOf(location.getLatitude()))) {
                    if ("en".equals(mEns)) {
                        showToast("The location failed. Check that the location permission is open");
                    } else {
                        showToast("定位失败，请查看位置权限是否打开");
                    }
                    LocationManager.getInstance().stopRequestLocal();
                }
                lastDBLocation = location;
                LocationManager.getInstance().stopRequestLocal();
                LocationManager.log(lastDBLocation);
                refreshTvAddress();
                //前面是经度 后面是纬度
                zuobiao = location.getLongitude() + "," + location.getLatitude();
                if (isSave) {
                    dismissWainting();
                    mapList();
                    sendDate();
                }

            } else {
                if (null != location) {
                    if ("en".equals(mEns)) {
                        showToast("Location failed, please try again!:" + location.getLocType());
                    } else {
                        showToast("定位失败，请重试! 错误码:" + location.getLocType());
                    }

                }
            }
        }
    };

    @Override
    public void changeJxs(String names, String jxsId) {
        jxsBull.setText(names);
        this.jxsId = jxsId;
    }

    @Override
    public void changeMd(String names, String id) {
        mdBull.setText(names);
        mdid = id;
    }

    @Override
    public void changeGzlx(String names) {
        if("门店拜访".equals(names)){
            imageArray.clear();
            imageArray2.clear();
            imageArray3.clear();
            imageArray4.clear();
            image1Bull.setImageResource(R.drawable.bullimagebg);
            image2Bull.setImageResource(R.drawable.bullimagebg);
            image3Bull.setImageResource(R.drawable.bullimagebg);
            image4Bull.setImageResource(R.drawable.bullimagebg);

        }
        bullJobType.setText(names);
        if("工作日报".equals(names)||"工作记录".equals(names)||"非固定线".equals(names)){
            ll_jxs_md.setVisibility(View.GONE);
        }else {
            ll_jxs_md.setVisibility(View.VISIBLE);
        }


    }

    // 把数据转换成json格式。用于上传服务端
    private void mapList() {
        jsonlist = new HashMap<String, String>();
//        zcmc_bull.setText(data.zcmc);
//        zclx_bull.setText(data.zclx);


        if("工作日报".equals(bullJobType.getText().toString())||"工作记录".equals(bullJobType.getText().toString())||"非固定线".equals(bullJobType.getText().toString())){

        }else {
            jsonlist.put("jxs", jxsId);
            jsonlist.put("md", mdid);
        }
        jsonlist.put("qkms", qkmsBull.getText().toString());
        jsonlist.put("gzlx", bullJobType.getText().toString());
        jsonlist.put("czsj", starttime.getText().toString());
        jsonlist.put("wwzb", zuobiao);
        jsonlist.put("dd", bullAddressTv.getText().toString());
        jsonlist.put("sj", starttime.getText().toString());
        jsonlist.put("jssj", endtime.getText().toString());
//        jsonlist.put("dymendian",data.ssmendianccname);
//        jsonlist.put("czdd",data.tfdz);
//        jsonlist.put("name",data.name);
        //营销资产id
//        jsonlist.put("yxzc",data.recordtype);
        System.out.println(jsonlist);
    }

    private void sendDate() {
        if ("en".equals(mEns)) {
            showWainting("Uploading image...");
        } else {
            showWainting("正在上传图片...");
        }

        if (imageArray.size() > 0) {
            imageArrayAll.add(imageArray.get(0));
        }
        if (imageArray2.size() > 0) {
            imageArrayAll.add(imageArray2.get(0));
        }
        if (imageArray3.size() > 0) {
            imageArrayAll.add(imageArray3.get(0));
        }
        if (imageArray4.size() > 0) {
            imageArrayAll.add(imageArray4.get(0));
        }
        if (imageArrayAll.size() < 1) {
            Toast.makeText(BullNewJobActivity.this, "图片数量不能少于1", Toast.LENGTH_SHORT).show();
            dismissWainting();
            return;
        }
        Log.d("---imageArrayAll", imageArrayAll.size() + "-");
        dynamicControl.sendPhotoBull(imageArrayAll, jsonlist, isxunjian);
    }

    public void onEventMainThread(DynamicEventList.SendDynamicEvent event) {
        dismissWainting();
        if (event.isError()) {
            if (event.getStatusCode() == BaseEvent.SC_LOGIN_INVAILED) {// 登录失效
                Intent intent = new Intent(mContext, BindActivity.class);
                mContext.startActivity(intent);
            } else if (event.getStatusCode() == BaseEvent.NET_NO_NETWORK) {// 没有网络
                if ("en".equals(mEns)) {
                    Tools.showInfo(mContext, "No network yet...");
                } else {
                    Tools.showInfo(mContext, "暂无网络...");
                }

            } else if (event.getMessage() != null) {
                String rtunrninfo = event.getMessage();
                Toast.makeText(mContext, rtunrninfo.substring(rtunrninfo.indexOf("：") + 1, rtunrninfo.length()), Toast.LENGTH_LONG).show();

            } else {
                if ("en".equals(mEns)) {
                    Tools.showInfo(mContext, "Posted  failure");
                } else {
                    Tools.showInfo(mContext, "发布失败");
                }

                finish();
            }
            return;
        }
        RunTimeManager.getInstance().setGongniu("jilu");
        finish();

    }

    public void takePhoto(int photo) {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File(Environment.getExternalStorageDirectory() + "/"
                    + "CloudCC/photo/");
            if (!dir.exists())
                dir.mkdirs();
            imagename = Tools.getTimeName(System.currentTimeMillis());
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            File f = new File(dir, imagename+".jpg");// localTempImgDir和localTempImageFileName是自己定义的名字
            filePaths = Environment.getExternalStorageDirectory() + "/CloudCC/photo/";
            Uri u;
            String filePaths1 = filePaths + "/"+imagename+".jpg";
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  //针对Android7.0，需要通过FileProvider封装过的路径，提供给外部调用
                u = FileProvider.getUriForFile(this, AppUtil.getFileProviderAuthority(this), new File(filePaths1));//通过FileProvider创建一个content类型的Uri，进行封装
            } else {
                u = Uri.fromFile(f);
            }
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
            startActivityForResult(intent, photo);
        } else {
            Tools.showInfo(mContext, "请插入SD卡");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode!=RESULT_OK){
            return;
        }

        File f = new File(Environment.getExternalStorageDirectory()
                + "/" + "CloudCC" + "/photo/" + imagename+".jpg");
        switch (requestCode) {
            case TAKE_PHOTO_1:
                if (isTp) {
                    try {
                        Uri u = Uri.parse(MediaStore.Images.Media
                                .insertImage(getContentResolver(),
                                        f.getAbsolutePath(), "IMG"+ Calendar.getInstance().getTime(), null));
                        String imageurl = getAbsoluteImagePathx(u);
                        AddImageInfo imageInfo = new AddImageInfo();
                        imageInfo.setImagePath(shuiyin(imageurl));
                        imageArray.clear();
                        imageArray.add(imageInfo);
                        ImageLoader.getInstance().displayImage("file://" + imageInfo.getImagePath(), image1Bull,
                                Constants.IM_IMAGE_OPTIONS, animateFirstListener);
                    } catch (FileNotFoundException e) {
                        Tools.handle(e);
                    }
                } else {
                    pickRes(1, data);
                }
                break;
            case TAKE_PHOTO_2:
                if (isTp) {
                    try {
                        Uri u = Uri.parse(MediaStore.Images.Media
                                .insertImage(getContentResolver(),
                                        f.getAbsolutePath(), "IMG"+ Calendar.getInstance().getTime(), null));
                        String imageurl = getAbsoluteImagePathx(u);

                        AddImageInfo imageInfo = new AddImageInfo();
                        imageInfo.setImagePath(shuiyin(imageurl));
                        imageArray2.clear();
                        imageArray2.add(imageInfo);
                        ImageLoader.getInstance().displayImage("file://" + imageInfo.getImagePath(), image2Bull,
                                Constants.IM_IMAGE_OPTIONS, animateFirstListener);
                    } catch (FileNotFoundException e) {
                        Tools.handle(e);
                      //  Log.e("---e",e.toString());
                    }
                } else {
                    pickRes(2, data);
                }
                break;
            case TAKE_PHOTO_3:

                if (isTp) {
                    try {
                        Uri u = Uri.parse(MediaStore.Images.Media
                                .insertImage(getContentResolver(),
                                        f.getAbsolutePath(), "IMG"+ Calendar.getInstance().getTime(), null));
                        String imageurl = getAbsoluteImagePathx(u);

                        AddImageInfo imageInfo = new AddImageInfo();
                        imageInfo.setImagePath(shuiyin(imageurl));
                        imageArray3.clear();
                        imageArray3.add(imageInfo);
                        ImageLoader.getInstance().displayImage("file://" + imageInfo.getImagePath(), image3Bull,
                                Constants.IM_IMAGE_OPTIONS, animateFirstListener);
                    } catch (FileNotFoundException e) {
                        Tools.handle(e);
                    }
                } else {
                    pickRes(3, data);
                }
                break;
            case TAKE_PHOTO_4:
                if (isTp) {
                    try {
                        Uri u = Uri.parse(MediaStore.Images.Media
                                .insertImage(getContentResolver(),
                                        f.getAbsolutePath(), "IMG"+ Calendar.getInstance().getTime(), null));
                        String imageurl = getAbsoluteImagePathx(u);

                        AddImageInfo imageInfo = new AddImageInfo();
                        imageInfo.setImagePath(shuiyin(imageurl));
                        imageArray4.clear();
                        imageArray4.add(imageInfo);

                        ImageLoader.getInstance().displayImage("file://" + imageInfo.getImagePath(), image4Bull,
                                Constants.IM_IMAGE_OPTIONS, animateFirstListener);

                        //   setPhotos4();
                    } catch (FileNotFoundException e) {
                        Tools.handle(e);
                    }
                } else {
                    pickRes(4, data);
                }
                break;
        }


        super.onActivityResult(requestCode, resultCode, data);
    }

    private String shuiyin(String imageurl) {
        // 将图片加上水印
        Bitmap sourBitmap = ImageUtil.getDiskBitmap(imageurl);
        String name = "By"
                + UserManager.getManager().getUser().userName;
        String time = Tools.getTime2(System.currentTimeMillis());

//                String address = currentLoc.getAddress();
        String address = bullAddressTv.getText().toString();
        // Bitmap fugai =
        // BitmapFactory.decodeResource(getResources(), R.id.a);
        String address1 = null;
        String address2 = null;
        Bitmap textBitmap = ImageUtil.drawTextToLeftBottom(this,
                sourBitmap, name, 60, Color.WHITE, 20, 240);
        textBitmap = ImageUtil.drawTextToLeftBottom(this,
                textBitmap, time, 60, Color.WHITE, 20, 170);
        textBitmap = ImageUtil.drawTextToLeftBottom(this,
                textBitmap, "", 60, Color.WHITE, 20, 95);
        if (address.length() > 20) {
            address1 = address.substring(0, 20);
            address2 = address.substring(11, address.length());
            textBitmap = ImageUtil.drawTextToLeftBottom(this,
                    textBitmap, address1, 60, Color.WHITE, 20, 100);
            textBitmap = ImageUtil.drawTextToLeftBottom(this,
                    textBitmap, address2, 60, Color.WHITE, 20, 30);

        } else {
            textBitmap = ImageUtil.drawTextToLeftBottom(this,
                    textBitmap, address, 60, Color.WHITE, 20, 30);
        }

        // 存储图片
        savePhotoToSDCard(Environment.getExternalStorageDirectory()
                        + "/" + "CloudCC" + "/photo", imagename + ".jpg",
                textBitmap);

        imageurl = Environment.getExternalStorageDirectory() + "/"
                + "CloudCC" + "/photo/" + imagename + ".jpg";
        return imageurl;
    }

    private void pickRes(int i, Intent data) {
        Uri photoUri = geturi(data);
        //获取照片路径
        String[] filePathColumn = {MediaStore.Audio.Media.DATA};
        Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null);
        cursor.moveToFirst();
        String str = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
        cursor.close();
        String str1 = null;
        switch (i) {
            case 1:
                str1 = ImgSmallUtils.compressImage(this, str, Environment.getExternalStorageDirectory()
                        + "/" + "CloudCC" + "/photo" + "/img_s1.jpg", 50, "");
                AddImageInfo imageInfo = new AddImageInfo();
                imageInfo.setImagePath(str1);
                imageArray.clear();
                imageArray.add(imageInfo);
                Bitmap bitmap = BitmapFactory.decodeFile(str1);
                image1Bull.setImageBitmap(bitmap);
                break;
            case 2:
                str1 = ImgSmallUtils.compressImage(this, str, Environment.getExternalStorageDirectory()
                        + "/" + "CloudCC" + "/photo" + "/img_s2.jpg", 50, "");
                AddImageInfo imageInfo2 = new AddImageInfo();
                imageInfo2.setImagePath(str1);
                imageArray2.clear();
                imageArray2.add(imageInfo2);
                Bitmap bitmap2 = BitmapFactory.decodeFile(str1);
                image2Bull.setImageBitmap(bitmap2);
                break;
            case 3:
                str1 = ImgSmallUtils.compressImage(this, str, Environment.getExternalStorageDirectory()
                        + "/" + "CloudCC" + "/photo" + "/img_s3.jpg", 50, "");
                AddImageInfo imageInfo3 = new AddImageInfo();
                imageInfo3.setImagePath(str1);
                imageArray3.clear();
                imageArray3.add(imageInfo3);
                Bitmap bitmap3 = BitmapFactory.decodeFile(str1);
                image3Bull.setImageBitmap(bitmap3);
                break;
            case 4:
                str1 = ImgSmallUtils.compressImage(this, str, Environment.getExternalStorageDirectory()
                        + "/" + "CloudCC" + "/photo" + "/img_s4.jpg", 50, "");
                AddImageInfo imageInfo4 = new AddImageInfo();
                imageInfo4.setImagePath(str1);
                imageArray4.clear();
                imageArray4.add(imageInfo4);
                Bitmap bitmap4 = BitmapFactory.decodeFile(str1);
                image4Bull.setImageBitmap(bitmap4);
                break;
        }


    }


    /**
     * 解决小米手机上获取图片路径为null的情况
     *
     * @param intent
     * @return
     */
    public Uri geturi(Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }

    public String getAbsoluteImagePathx(Uri uri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(uri, proj, // Which columns to return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    private void setPhotos2() {
        List<String> selectedImagePathArray = AppContext.selectPhotos;
        if (imageArray2.size() + selectedImagePathArray.size() > 9) {
            selectedImagePathArray.clear();
            if ("en".equals(mEns)) {
                Tools.showInfo(mContext, "Add up to 9 images");
            } else {
                Tools.showInfo(mContext, "最多添加9张图片");
            }

            return;
        }
        for (String imagePath : selectedImagePathArray) {
            if (imageArray2.contains(imagePath)) {// 去重
                continue;
            }
            AddImageInfo imageInfo = new AddImageInfo();

            imageInfo.setImagePath(imagePath);
            imageArray2.add(imageInfo);
        }
        AddImageInfo localImageInfo = imageArray2.get(0);
//        adapter = new AddmicroPostGridviewAdapter(mContext, imageArray);
//        containerGridViewPhoto.setAdapter(adapter);
//        setAdapterListener();
        ImageLoader.getInstance().displayImage("file://" + localImageInfo.getImagePath(), image2Bull,
                Constants.IM_IMAGE_OPTIONS, animateFirstListener);
        selectedImagePathArray.clear();
    }


    public void savePhotoToSDCard(String path, String photoname, Bitmap pBitmap) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                File dir = new File(path);
                if (!dir.exists())
                    dir.mkdirs();
                File photoFile = new File(path, photoname);
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(photoFile);
                    if (pBitmap != null) {
                        if (pBitmap.compress(Bitmap.CompressFormat.JPEG, 25,
                                fileOutputStream)) {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                } finally {
                    try {
                        fileOutputStream.close();
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }
            }
        }
    }

    private void getJxs() {
        String expressions = "id='" + mdid + "'";
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "cquery");//普通插入服务
        params.addBodyParameter("objectApiName", "mendian");
        params.addBodyParameter("expressions", expressions);
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        // showDialog.onDismissLoadingDialog();
                        //  Toast.makeText(ShopAddressActivity.this, "新建门店出错", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        com.litesuits.android.log.Log.d("---res", arg0.result);
                        try {
                            JSONObject myJsonObject = new JSONObject(arg0.result);
                            String result = myJsonObject.getString("result");
                            String returnInfo = myJsonObject.getString("returnInfo");
                            String data = myJsonObject.getString("data");
                            if (result.equals("true")) {
                                Gson gson = new Gson();
                                List<ShopBean> appList = gson.fromJson(data, new
                                        TypeToken<List<ShopBean>>() {
                                        }.getType());
                                if (appList.size() > 0) {
                                    // String zb=appList.get(0).getDzzb();
                                    //tvShopName.setText(appList.get(0).getName());
                                    jxsBull.setText(appList.get(0).getDyjxsccname());
                                    jxsId = appList.get(0).getDyjxs();
                                    Log.d("---jxsId", jxsId + "--");

                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }
                        //  showDialog.onDismissLoadingDialog();
                    }
                });

    }
}
